package com.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.bean.UserInfoBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.ResponseResult;
import com.lovo.result.ResultCode;
import com.lovo.result.UserValid;
import com.lovo.service.IUserInfoService;
import com.lovo.util.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bdk
 * @since 2021-03-02
 */
@RestController
@RequestMapping("/users")
@ResponseResult
@Api("用户注册和登录以及查看用户信息的控制器")
public class UserInfoController {
    @Resource
    private IUserInfoService userInfoService;
    @PostMapping("/register")
    @ApiOperation(value = "注册请求")
    public Object register(@RequestBody UserInfoBean userInfoBean){
        // 使用SHA256加密
        userInfoBean.setUserPass(DigestUtils.sha256Hex(userInfoBean.getUserPass()));
        userInfoService.save(userInfoBean);
        return null;
    }
    @ApiOperation(value = "显示所有用户")
    @GetMapping
    @UserValid
    public Object showAll(Integer page,Integer size) throws GlobalHandleException {
//        Subject currentUser = SecurityUtils.getSubject();
//        if(currentUser.hasRole("系统管理员") || currentUser.isPermitted("查看用户")){
//            return userInfoService.selectAll(page,size);
//        }else{
//            throw new GlobalHandleException(ResultCode.USER_AUTHORIZATION_ERROR);
//        }
        return userInfoService.selectAll(page,size);
    }
    @PostMapping
//    @RequiresRoles({"系统管理员"})
    public Object add(){
        return "add用户";
    }

    @ApiOperation("登录方法")
    @PostMapping("/login")
    public Object login(String userName, String userPass) throws GlobalHandleException {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_name",userName);
        wrapper.eq("user_pass",DigestUtils.sha256Hex(userPass));
        UserInfoBean userInfoBean = userInfoService.getOne(wrapper);
        if(userInfoBean == null){
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }

//        session.setAttribute("user",userInfoBean);
        String token = JWTUtil.createToken(userInfoBean.getUserName(),userInfoBean.getUserPass(), Calendar.MINUTE,30);
        String refreshToken = JWTUtil.createToken(userInfoBean.getUserName().toString(),userInfoBean.getUserPass(), Calendar.DATE,7);
        Map map = new HashMap();
        map.put("token",token);
        map.put("refreshToken",refreshToken);
        return map;
        // 把用户输入的账号和密码封装到shiro框架提供的token对象中
//        UsernamePasswordToken token = new UsernamePasswordToken(userName, DigestUtils.sha256Hex(userPass));
//        Subject currentUser = SecurityUtils.getSubject();
//        try{
//            //主体提交登录请求到SecurityManager
//            currentUser.login(token);
//        }catch(IncorrectCredentialsException ice){
//            throw new GlobalHandleException(ResultCode.USER_PASS_ERROR);
//        }catch (UnknownAccountException uae){
//            throw new GlobalHandleException(ResultCode.USER_NOT_EXIST);
//        }catch (AuthenticationException ae){
//            throw new GlobalHandleException(ResultCode.USER_AUTHENTICATION_ERROR);
//        }catch (AuthorizationException ae){
//            throw new GlobalHandleException(ResultCode.USER_AUTHORIZATION_ERROR);
//        }
//        return currentUser.getPrincipal();

    }

    @GetMapping("/removeSession")
    public Object removeSession(HttpSession session){
        session.setAttribute("user",null);
        return null;
    }

    /**
     * 从session中获取用户对象
     * @return
     */
    @GetMapping("/session")
    @UserValid
    public Object getUserWithSession(HttpSession session){
        return session.getAttribute("user");
    }
    /**
     * 从token中获取用户对象
     * @return
     */
    @GetMapping("/token")
    @UserValid
    public Object getUserWithToken(HttpServletRequest request){
        return SecurityUtils.getSubject().getPrincipal();
    }

    @GetMapping("/refreshToken")
    @UserValid
    public Object refreshToken(HttpServletRequest request){
        UserInfoBean userInfoBean = (UserInfoBean) request.getAttribute("user");
        return JWTUtil.createToken(userInfoBean.getUserId().toString(),userInfoBean.getUserPass(),Calendar.SECOND,10);
    }
}

